<template>
  <div class="pic-upload" :class="{radius:radius}"  v-loading="loading">
    <el-upload v-bind="$attrs" v-on="$listeners" class="avatar-uploader"   action="/api/Home/SystemMenu/uploadFilmImage" :show-file-list="false" :on-success="handleSuccess"  accept="image/*" name="fileData" :before-upload="beforeUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" >
      <i v-else class="el-icon-plus avatar-uploader-icon"/>
    </el-upload>
     <span v-if="content" class="content">{{ content }}</span>
    </div>
</template>

<script>
export default {
  props: {
    content: String,
    size: {
      type: Number,
      default: 2
    },
    value: String,
    radius: Boolean
  },
  data () {
    return {
      imageUrl: '',
      loading: false
    }
  },
  watch: {
    value (val) {
      if (val !== this.imageUrl) {
        this.imageUrl = val
      }
    }
  },
  methods: {
    handleSuccess (res, file) {
      this.loading = true
      if (res.status === 0) {
        this.loading = false
        this.$emit('input', res.data.url)
        this.imageUrl = URL.createObjectURL(file.raw)
      } else {
        this.loading = false
        this.$message.error('上传失败')
        this.$emit('input', '')
      }
    },
    beforeUpload (file) {
      this.loading = true
      const isLtSize = file.size / 1024 / 1024 < this.size
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isLtSize) {
        this.$message.error(`上传图片大小不能超过 ${this.size}MB!`)
      }
      if (!isJPG) {
        this.$message.error('上传图片只能是  JPG和 PNG 格式!')
      }
      return isLtSize
    }
  },
  created () {
    if (this.value) {
      this.imageUrl = this.value
    }
  }
}
</script>
<style lang="scss" scoped>
.pic-upload {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.avatar-uploader {
  height: 152px;
  width: 152px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.content {
  color: #c0c4cc;
  font-size: 14px;
}
</style>
<style lang="scss">
.pic-upload {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
  &.radius .el-upload{
    border-radius: 50%;
  }
}
</style>
